home *** CD-ROM | disk | FTP | other *** search
- Path: news.interport.net!scamhi
- From: scamhi@interport.net (Steven Camhi)
- Newsgroups: comp.lang.c++
- Subject: Simple elastic list in C++...
- Date: Mon, 08 Apr 96 04:23:25 GMT
- Organization: Interport Communications Corp.
- Message-ID: <4ka4d5$cia@park.interport.net>
- NNTP-Posting-Host: scamhi.port.net
- Mime-Version: 1.0
- Content-Type: text/plain; charset=US-ASCII
- X-Newsreader: News Xpress 2.0 Beta #0
-
- As a programmer old to C, new to C++, I have seen no 'simple' answer to the
- following situation. In most cases, the easiest, simplest way (for me, that
- is), to create a growable list in straight ANSI C, has been the following:
-
- typedef struct MyDataS
- {
- ..
- } MyDataT;
-
- void MyFunction()
- {
- int allocCount = 0;
- int rowsRead = 0;
- int moreElements;
- MyDataT *listPtr;
-
- for (moreElements = 1; moreElements; rowsRead++)
- {
- if (allocCount == rowsRead)
- {
- if (allocCount == 0)
- listPtr = malloc(sizeof(MyDataT) *
- (allocCount += 10));
- else
- listPtr = realloc(listPtr, sizeof(MyDataT) *
- (allocCount += 10));
- if (listPtr == NULL)
- /*
- * Do some error handling here.
- */
- }
- moreElements = ReadAnElement(&listPtr[rowsRead]);
- }
- }
-
- (Sorry if the syntax is off a little, you get the jist... :))
-
- Anyway, this model has worked for me because, you can now go ahead and further
- bsearch and qsort away to your hearts content, without fancy 'next pointer'
- fields and all that hassle.
-
- What is *the best* way of doing dynamically growable lists in C++, without a
- headache? Perhaps there is no *best* way, what is the way to approach the
- problem of manufacturing a simple list class. One way I have seen is the use
- of the STL vector classes; thats been my frame of reference.
-
- Most books I've read show a simple example of C++ by implementing a stack in
- C++ which inside contains a fixed size array. This has never been a 'real
- world' example for me.
-
- I've seen some examples on the net use realloc(), and I've heard thats a major
- no-no! Whats the right way?
-
- If this is in a FAQ sorry in advance....
-
- TIA
- Steve Camhi
- scamhi@interport.net
-